#!/usr/bin/env bash

# shellcheck disable=SC2034
current_dir="$(cd "$(dirname "$0")" && pwd)"

env_file=".env"
env_example_file=".env.example"
date_time=$(date '+%Y-%m-%d_%H-%M-%S')
docker_compose_file="$current_dir/docker-compose.yaml"
service_dir="/data0/services"
backup_dir="$current_dir/backup"

install_env_file(){

    if [ ! -d "$backup_dir" ]; then
        mkdir -p "$backup_dir"
    fi

    if [ -f "$env_file" ]; then
        cp $env_file "$backup_dir/$env_file.bak_${date_time}"
    fi

    cp $env_example_file $env_file

    secret_key=$(openssl rand -base64 42)
    # 随机生成数据库密码
    db_passwd=$(openssl rand -base64 12)
    # 如果是MacOS
    if [[ "$OSTYPE" =~ ^darwin ]]; then
        sed -i '' "/^SECRET_KEY=/c\\
SECRET_KEY=${secret_key}" "$env_file"
        sed -i '' "/^DB_PASSWORD=/c\\
DB_PASSWORD=${db_passwd}" "$env_file"
    else
        sed -i "/^SECRET_KEY=/c\\
SECRET_KEY=${secret_key}" "$env_file"
        sed -i "/^DB_PASSWORD=/c\\
DB_PASSWORD=${db_passwd}" "$env_file"
    fi
}

install_docker_images() {
    # shellcheck disable=SC2002
    docker_images=$(
      grep 'image[[:space:]]*:[[:space:]]*' "$docker_compose_file" | # 读取 image: image-name
      sed 's/dify-api-with-ocr/dify-api/g' |    # 临时替换
      awk -F'image[[:space:]]*:[[:space:]]*' '{ gsub(/^[[:space:]]+|[[:space:]]+$/, "", $2); print $2 }' | # 匹配镜像名称
      awk '!seen[$0]++' | # 去重复
      sort -u
    )
    for image_name in $docker_images; do
        # ocr 需单独处理
        # shellcheck disable=SC2252
        if [ "ocr-service" != "$image_name" ]; then
            real_image_url="docker.m.daocloud.io/${image_name}"
            echo "pull docker image : ${real_image_url}"
            docker pull "$real_image_url"
            docker tag "$real_image_url" "$image_name"
            docker rmi "$real_image_url"
        fi
    done

    if [ ! -d "${service_dir}" ]; then
        mkdir -p "${service_dir}"
    fi

    echo "install ocr service"
    # shellcheck disable=SC2164
    cd "$service_dir"

    # ocr runtime
    git clone https://gitee.com/kernelstudio/docker-cuda-ocr-runtime
    # shellcheck disable=SC2164
    cd docker-cuda-ocr-runtime
    sh build.sh

    # cor service
    # shellcheck disable=SC2164
    cd "$service_dir"
    git clone https://gitee.com/kernelstudio/ocr-service
    # shellcheck disable=SC2164
    cd ocr-service
    sh build.sh

    # cor patch
    # shellcheck disable=SC2164
    cd "$service_dir"
    git clone https://gitee.com/kernelstudio/dify-api-with-ocr
    # shellcheck disable=SC2164
    cd dify-api-with-ocr
    sh build.sh
}

main(){
    install_env_file
    install_docker_images
}

main